package com.archstoday.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.archstoday.R;
import com.base.activity.BaseActivity;
import com.base.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 写文章页面添加图片适配器
 */
public class SendArticleAdapter extends BaseAdapter {

    private Context mContext;
    private BaseActivity.Click mClick;
    private List<Bitmap> mData;

    public SendArticleAdapter(Context context, BaseActivity.Click click) {
        mContext = context;
        mClick = click;
    }

    public void addData(Bitmap img) {
        if (mData == null) {
            mData = new ArrayList<>();
        }
        mData.add(img);
        notifyDataSetChanged();
    }

    public void removeData(Bitmap img) {
        if (mData != null) {
            mData.remove(img);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getCount() {
        if (mData == null) {
            return 1;
        } else if (mData.size() == 5) {
            return mData.size();
        }
        return mData.size() + 1;
    }

    @Override
    public Bitmap getItem(int i) {
        return mData.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Holder holder;
        if (view == null) {
            holder = new Holder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_add_img, null);
            holder.img = (ImageView) view.findViewById(R.id.item_img);
            holder.delBtn = (TextView) view.findViewById(R.id.item_del_btn);

            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        if (mData == null) {
            holder.img.setImageResource(R.mipmap.add_img_icon);
            holder.delBtn.setVisibility(View.GONE);
        } else {
            if (i < mData.size()) {
                holder.img.setImageBitmap(mData.get(i));
                holder.delBtn.setVisibility(View.VISIBLE);
            } else {
                holder.img.setImageResource(R.mipmap.add_img_icon);
                holder.delBtn.setVisibility(View.GONE);
            }
        }

        holder.delBtn.setTag(i);
        holder.delBtn.setOnClickListener(mClick);

        return view;
    }

    class Holder {
        ImageView img;
        TextView delBtn;
    }

}